package org.helyx.gae.getabike.provider.details;

import java.io.BufferedInputStream;
import java.io.InputStream;

import org.helyx.gae.getabike.content.accessor.ContentAccessor;
import org.helyx.gae.getabike.content.provider.ParameterizedContentProvider;
import org.helyx.gae.getabike.content.provider.exception.ContentProviderException;
import org.helyx.gae.getabike.model.City;
import org.helyx.gae.getabike.model.StationDetails;
import org.helyx.gae.getabike.provider.AbstractStationContentProvider;
import org.helyx.gae.util.stream.InputStreamProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;

public abstract class AbstractStationDetailsContentProvider implements ParameterizedContentProvider<StationDetails, String>, InitializingBean {

	private static final Logger LOGGER = LoggerFactory.getLogger(AbstractStationContentProvider.class);

	protected ContentAccessor contentAccessor;

	protected City city;
	
	public AbstractStationDetailsContentProvider() {
		super();
	}
	
	public void setContentAccessor(ContentAccessor contentAccessor) {
		this.contentAccessor = contentAccessor;
	}

	public void setCity(City city) {
		this.city = city;
	}

	public ContentAccessor getContentAccessor() {
		return contentAccessor;
	}

	public City getCity() {
		return city;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		Assert.notNull(city, "[Assertion failed] - city is required; it must not be null");
		Assert.notNull(contentAccessor, "[Assertion failed] - contentAccessor is required; it must not be null");
	}
	
	public StationDetails getContent(String stationId) throws ContentProviderException {
		
		InputStream inputStream = null;
		InputStreamProvider inputStreamReaderProvider = null;
	
		try {
			inputStreamReaderProvider = contentAccessor.getInputStreamProvider();	
			inputStream = new BufferedInputStream(inputStreamReaderProvider.createInputStream());

			StationDetails stationDetails = getStationDetails(inputStream, stationId);
			
			return stationDetails;
		}
		catch (Exception e) {
    		LOGGER.warn(e.getMessage(), e);
			throw new ContentProviderException(e);
		}
		
	}

	protected abstract StationDetails getStationDetails(InputStream inputStream, String stationId) throws ContentProviderException;

}
